package site.brood.user.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import site.brood.common.core.constant.Constants;
import site.brood.user.mapper.UserMapper;
import site.brood.user.pojo.entity.Role;
import site.brood.user.pojo.entity.User;
import site.brood.user.service.IUserService;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    public List<String> selectRolesByUserId(Long userId) {
        List<Role> roles = this.baseMapper.selectRolesByUserId(userId);
        List<String> roleNames = roles.stream().map(Role::getRoleKey).collect(Collectors.toList());
        return roleNames;
    }

    public Set<String> selectMenuPermsByUserId(Long userId) {
        Set<String> perms = this.baseMapper.selectMenuPermsByUserId(userId);
        return perms;
    }

    public boolean checkUsernameValid(String username) {
        List<User> list = new LambdaQueryChainWrapper<User>(this.baseMapper)
                .eq(User::getUsername, username)
                .list();
        return list.size()<1;
    }

    @Override
    public boolean isAdmin(Long userId) {
        if(null != userId)
            return false;

        List<Role> roles = this.baseMapper.selectRolesByUserId(userId);
        if(null == roles)
            return false;

        Optional<Role> adminRole = roles.stream()
                .filter(item -> item.getRoleKey().equals(Constants.ROLE_SUPER_ADMIN))
                .findFirst();
        return adminRole.isPresent();
    }

    public boolean add(User user){
        int rowCount = this.baseMapper.insert(user);
        return rowCount>0;
    }
}
